import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author 支绍昆
 * 2022/8/15
 * 内存使用情况
 **/
public class MemoryUsageExample {

    public static void main(String[] args) {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

        //打印内存情况
        new Thread(() -> {
            int i = 0;
            while (i < 20) {

                MemoryUsage mem = memoryMXBean.getHeapMemoryUsage();
                i++;
                System.out.println("Committed(" + mem.getCommitted() / 1024  + "KB)"
                        + " Init(" + mem.getInit() / 1024  + "KB)"
                        + " Used(" + mem.getUsed() / 1024  + "KB)"
                        + " max(" + mem.getMax() / 1024  + "KB)");


                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        //占用内存
        List<List<Integer>> all = new ArrayList<>();
        new Thread(()->{
            for (int i=0; i<20; i++){
                System.out.println(Integer.toBinaryString(i));
                List<Integer> l = new ArrayList<>(100000);
                Random random = new Random();
                for (int n=0;n<100000;n++){
                    l.add(random.nextInt());
                }
                all.add(l);

                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

}
